package org.emet.flex.services
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	//here is the key object - you need to import THIS exact remote object
	import mx.rpc.remoting.mxml.RemoteObject;
	
	[Event(name="complete",type="flash.events.Event")]
	[Event(name="error",type="flash.events.ErrorEvent")]
	
	/**
	 * Remote operation class used to call any remote object, depending
	 * on the parameters supplied. Also will process the result using
	 * the response handler for any supplied VO
	 */
	public class AbstractRemoteOperation
	{
		
		/** The remote object performing the request on behalf of this operation. */
		public var ro:RemoteObject = null;
		
		/**result object - processes the php result and catches all errors**/
		[Bindable]
		public var responseHandler:AMFResponseHandler;
		
		/**
		 * Constructor for the AbstractRemoteOperation.
		 * This will never be called except as a super() method by a child object
		 * */
		public function AbstractRemoteOperation(destination:String,source:String,endpoint:String, className:Class) : void
		{
			ro = new RemoteObject();
			
			ro.destination = destination;
			ro.source = source;
			ro.endpoint = endpoint;
			ro.showBusyCursor = false;
			
			responseHandler = new AMFResponseHandler();
			responseHandler.setClassName(className);
			
		}
		
		protected function handleFault(e:Event):void
		{
			removeEventListeners();
			responseHandler.error = "Internal Error";
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
		}
		
		/**
		 * Check to see if we have a valid object and return it
		 */
		protected function handleComplete(e:Event):void
		{
			removeEventListeners();
			responseHandler.handleComplete(e);
			if ( responseHandler.error != "" ){
				dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
			}
			else {
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		protected function removeEventListeners () : void {
			
		}
		
	}

}